<template>
  <div class="account-wrap">
    <el-button class="el-add-btn" @click="addAccountVisible = true">新增</el-button>
    <div class="table-wrap">
      <mer-table :loading="tableLoading"
        :tableConfig="tableConfig"
        :tableData="tableData"
        :pagination="pagination"
        @SizeChange="handleSizeChange"
        @PageChange="pageChange"
        :hasIndex="true"
        :border="false">
        <template slot="dataPermission" slot-scope="{ row }">
          <div>
            {{ row.dataPermission && row.dataPermission.dataPermissionName || '' }}
          </div>
        </template>
        <template slot="status" slot-scope="{ row }">
          <div>
            {{ status[row.status] }}
          </div>
        </template>
        <template slot="createTime" slot-scope="{ row }">
          <div>
            {{ formatTime(row.createTime) }}
          </div>
        </template>
        <template slot="roleId" slot-scope="{ row }">
          <div>
            {{ roleList.find(item => item.roleId === row.roleId) ? roleList.find(item => item.roleId === row.roleId).roleName : '' }}
          </div>
        </template>
        <template slot="tradingTime" slot-scope="{row}">
          <div>
            <el-button class="table-mini-btn" :disabled="!row.canUpdate" @click="modify(row)">修改</el-button>
          </div>
        </template>
        <template slot="bindWx" slot-scope="{row}">
          <div v-if="!row.posWxBindStatus && !row.company">
            <el-button type="text" @click="initQRCode(row.userId)">生成二维码</el-button>
          </div>
          <div v-else-if="row.posWxBindStatus && !row.company">
            {{ row.posWxName || '' }}
            <el-button type="text" @click="unBindWx(row.userId)">解绑</el-button>
          </div>
          <div v-else></div>
        </template>
      </mer-table>
    </div>

    <!-- 新增账号 -->
    <el-dialog :visible.sync="addAccountVisible" center width="640px" :before-close="beforeClose('addForm')">
      <div slot="title" class="dialog-title">新增成员</div>
      <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px">
        <el-form-item label="姓名" prop="userName">
          <el-input :maxlength="10" v-model="addForm.userName" placeholder="请输入姓名" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile" maxlength="11" placeholder="请输入手机号" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model.trim="addForm.account" maxlength="50" placeholder="请输入账号" autocomplete="off" readonly @focus="removeAttr"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" autocomplete="off" maxlength="20" placeholder="请输入密码" readonly @focus="removeAttr"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="addForm.checkPass" autocomplete="off" maxlength="20" placeholder="请再次输入密码" readonly @focus="removeAttr"></el-input>
        </el-form-item>
        <div class="tips">
          <div class="title">登录密码规则：</div>
          <div class="des">• 密码必须同时含有大小写字母、数字、特殊字符（！、@、#、-、_）中的两种</div>
          <div class="des">• 密码的长度必须是8-20位</div>
          <div class="des">• 登录密码不能连续出现4个以及以上或相邻的，如0000，1234，abcd</div>
        </div>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="addForm.roleId" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="油站/商户" prop="groupId">
          <el-select v-model="addForm.groupId" placeholder="请选择油站/商户">
            <el-option v-for="item in stationList" :key="item.groupId" :label="item.groupName" :value="item.groupId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="btn-style" @click="back('addForm')">返回</el-button>
        <el-button class="btn-style primary" @click="addAccountSubmit" :loading="submitLoading" type="primary">提交</el-button>
      </div>
    </el-dialog>

    <!-- 修改账号 -->
    <el-dialog custom-class="dialog" :visible.sync="modifyVisible" center width="640px" :before-close="beforeClose('modifyForm')">
      <div slot="title" class="dialog-title">修改账号</div>
      <el-form :model="modifyForm" :rules="modifyRules" ref="modifyForm" label-width="120px">
        <el-form-item label="姓名" prop="userName">
          <el-input :maxlength="10" v-model="modifyForm.userName" placeholder="请输入姓名" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="modifyForm.mobile" maxlength="11" placeholder="请输入手机号" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modifyForm.email" placeholder="请输入邮箱" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model.trim="modifyForm.account" maxlength="50" placeholder="请输入账号" autocomplete="off" readonly @focus="removeAttr"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="modifyForm.password" autocomplete="off" maxlength="20" placeholder="请输入密码" readonly @focus="removeAttr"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="modifyForm.checkPass" autocomplete="off" maxlength="20" placeholder="请再次输入密码" readonly @focus="removeAttr"></el-input>
        </el-form-item>
        <div class="tips">
          <div class="title">登录密码规则：</div>
          <div class="des">• 密码必须同时含有大小写字母、数字、特殊字符（！、@、#、-、_）中的两种</div>
          <div class="des">• 密码的长度必须是8-20位</div>
          <div class="des">• 登录密码不能连续出现4个以及以上或相邻的，如0000，1234，abcd</div>
        </div>
        <el-form-item label="状态" required>
          <el-select v-model="modifyForm.status" placeholder="请选择状态">
          <el-option label="启用" :value="1"></el-option>
          <el-option label="禁用" :value="0"></el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="modifyForm.roleId" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属油站/商户" prop="groupId">
          <el-select v-model="modifyForm.groupId" placeholder="请选择油站/商户">
            <el-option v-for="item in stationList" :key="item.groupId" :label="item.groupName" :value="item.groupId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="btn-style" @click="back('modifyForm')">返回</el-button>
        <el-button class="btn-style primary" @click="modifySubmit" :loading="modifyLoading" type="primary">提交</el-button>
      </div>
    </el-dialog>

    <!-- 绑定微信 -->
    <el-dialog :visible.sync="bindWxVisible" center width="40%">
      <div ref="login_container" style="display: flex;justify-content: center;align-items: center;" id="login_container"></div>
      <div style="text-align: center;">请使用微信扫描二维码绑定</div>
    </el-dialog>
  </div>
</template>
<script>
import listPage from '@/mixins/listPage'
import { getList, addAccount, modifyAccount, roleList, getDataPermission, getAllDataPermissionGroup, unbindWxApi } from '@/api/gasStationManage/accountManage'
import validate from '@/utils/validate'
import dayjs from 'dayjs'
import MD5 from 'md5'
import WxLogin from 'WxLogin'

const TABLECONFIG = [
  {label: '油站/商户名称', prop: 'dataPermission', slot: 'dataPermission'},
  {label: '账号', prop: 'account',},
  {label: '姓名', prop: 'userName', width: '60'},
  {label: '手机号', prop: 'mobile'},
  {label: '绑定微信', prop: 'bindWx', slot: 'bindWx'},
  {label: '邮箱', prop: 'email'},
  {label: '角色', prop: 'roleName', width: '60'},
  {label: '创建时间', prop: 'createTime', slot: 'createTime'},
  {label: '状态', prop: 'status', slot: 'status', width: '60'},
  {label: '操作项', prop: 'tradingTime', slot: 'tradingTime', width: '80'}
]

export default {
  name: 'accountManage',
  mixins: [listPage],
  data () {
    // 验证电话
    const checkPhone = (rule, value, callback) => {
      if (value && !(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    // 邮箱校验
    const validateEmail = (rule, value, callback) => {
      const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if(value && !reg.test(value)){
        callback(new Error('请输入正确的邮箱'))
      }else{
        callback()
      }
    }
    return {
      tableLoading: false,
      tableConfig: TABLECONFIG,
      pagination: { pageNo: 1, pageSize: 10 },
      tableData: {
        total: 0,
        records: []
      },
      form: {
        username: '',
        mobile: ''
      },
      addAccountVisible: false,
      modifyVisible: false,
      addForm: {
        userName: '',
        mobile: '',
        roleId: '',
        groupId: '',
        email: '',
        account: '',
        password: '',
        checkPass: ''
      },
      modifyForm: {
        userId: '',
        mobile: '',
        status: '',
        groupId: '',
        userName: '',
        roleId: '',
        email: '',
        account: '',
        password: '',
        checkPass: ''
      },
      status: ['禁用', '启用'],
      roleList: [],
      stationList: [],
      addRules: {
        userName: [{ required: true, validator: validate.checkName, trigger: 'blur' }],
        mobile: [{ validator: checkPhone, trigger: 'blur' }],
        roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
        groupId: [{ required: true, message: '请选择油站/商户', trigger: 'change' }],
        email: [{ validator: validateEmail, trigger: 'blur' }],
        account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, validator: validate.validetePassword, trigger: 'blur' }],
        checkPass: [{ required: true, validator: this.valideteCheckPass('addForm'), trigger: 'blur' }],
      },
      modifyRules: {
        userName: [{ required: true, validator: validate.checkName, trigger: 'blur' }],
        mobile: [{ validator: checkPhone, trigger: 'blur' }],
        roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
        groupId: [{ required: true, message: '请选择油站/商户', trigger: 'change' }],
        email: [{ validator: validateEmail, trigger: 'blur' }],
        account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ validator: this.validetePassword, trigger: 'blur' }],
        checkPass: [{ validator: this.valideteCheckPass('modifyForm'), trigger: 'blur' }],
      },
      updateAdd: true,
      curLimit: 1, // 油站能否多选，1 只能选一个， 0 可以多选
      submitLoading: false,
      modifyLoading: false,
      bindWxVisible: false,
    }
  },
  methods: {
    async initTable () {
      this.tableLoading = true
      const params = {...this.form, ...this.pagination}
      try {
        const {code, result} = await getList(params)
        if (code !== 200) return
        this.tableData.records = result
      } catch (err) {
        console.log(err.message)
      } finally {
        this.tableLoading = false
      }
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.initTable()
    },
    pageChange (val) {
      this.pagination.pageNo = val
      this.initTable()
    },
    // 新增提交
    addAccountSubmit () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.addAccount()
        } else {
          return false
        }
      })
    },
    async addAccount () {
      try {
        this.submitLoading = true
        let { addForm } = this
        let params = Object.assign({}, addForm)
        params.password = MD5(params.password)
        delete params.checkPass
        const {code, result} = await addAccount(params)
        if (code !== 200) return
        if (result) {
          this.$message.success('提交成功')
          this.addAccountVisible = false
          this.resetForm('addForm')
          this.initTable()
        } else {
          this.$message.error('提交失败')
        }
      } catch (err) {
        console.log(err.message)
      } finally{
        this.submitLoading = false
      }
    },
    // 重置表格
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 修改
    modify (val) {
      this.checkDataPermission(val.userId)
    },
    // 查询账号下的数据权限
    async checkDataPermission (userId) {
      try {
        const {code, result} = await getDataPermission({userId})
        if (code !== 200) return
        Object.keys(this.modifyForm).forEach(key => {
          if (result[key]) this.modifyForm[key] = result[key]
        })
        this.modifyForm.userId = userId
        this.modifyVisible = true
      } catch (err) {
        console.log(err.message)
      }
    },
    // 修改提交
    modifySubmit () {
      this.$refs.modifyForm.validate((valid) => {
        if (valid) {
          this.modifyAccount()
        } else {
          return false
        }
      })
    },
    // 修改账号
    async modifyAccount () {
      try {
        this.modifyLoading = true
        let { modifyForm } = this
        let params = Object.assign({}, modifyForm)
        params.password ? params.password = MD5(params.password) : delete params.password
        delete params.checkPass
        const {code, result} = await modifyAccount(params)
        if (code !== 200) return
        if (result) {
          this.$message.success('修改成功')
          this.modifyVisible = false
          this.resetForm('modifyForm')
          this.initTable()
        } else {
          this.$message.error('修改失败')
        }
      } catch (err) {
        console.log(err.message)
      } finally{
        this.modifyLoading = false
      }
    },
    // 关闭前回调
    beforeClose (formName) {
      return (done) => {
        this.resetForm(formName)
        done()
      }
    },
    back (formName) {
      this.resetForm(formName)
      this.addAccountVisible = false
      this.modifyVisible = false
    },
    async getRoleList () {
      try {
        const {code, result} = await roleList()
        if (code !== 200) return
        this.roleList = result
        if (result?.length === 1) {
          this.addForm.roleId = result[0].roleId
        }
      } catch (err) {
        console.log(err.message)
      }
    },
    // 请求分组权限列表
    async getAllDataPermissionGroup () {
      try {
        const {code, result} = await getAllDataPermissionGroup()
        if (code !== 200) return
        this.stationList = result
        if (result?.length === 1) {
          this.addForm.groupId = result[0].groupId
        }
      } catch (err) {
        console.log(err.message)
      }
    },
    /**
     * @description 说明：切换select单选多选的时候需要用updateAdd控制是否显示，切换时需要设置为false，在数据更新后再渲染
     */
    // changeRole () {
      // this.updateAdd = false
      // this.addForm.dataPermission = ''
      // this.modifyForm.dataPermission = ''
      // this.addForm.dataPermission = value === 0 ? [] : ''
      // this.modifyForm.dataPermission = value === 0 ? [] : ''
      // this.roleList.map(item => {
      //   if (item.roleId === value) {
      //     this.curLimit = item.limit
      //     this.$nextTick(() => {
      //       this.updateAdd = true
      //     })
      //   }
      // })
    // },
    formatTime (time) {
      return dayjs(time).format('YYYY/MM/DD')
    },
    // 校验重复密码
    valideteCheckPass (form) {
      return (rule, value, callback) => {
        if (form === 'modifyForm') {
          if (this[form].password) {
            if (!value) {
              callback(new Error('请重复输入密码'))
            } else if (value !== this[form].password) {
              callback(new Error('两次输入密码不相同'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        } else {
          if (!value) {
            callback(new Error('请重复输入密码'))
          } else if (value !== this[form].password) {
            callback(new Error('两次输入密码不相同'))
          } else {
            callback()
          }
        }
      }
    },
    removeAttr (e) {
      e.target.removeAttribute('readonly')
    },
    validetePassword (rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      const reg = /^[a-zA-Z0-9！@#-_]{8,20}$/

      // 校验连续字符
      function validateContinue (str) {
        for (let i = 0; i < str.length; i++) {
          let num = str[i].charCodeAt()
          let continueStr = str[i] + String.fromCharCode(num + 1) + String.fromCharCode(num + 2) + String.fromCharCode(num + 3)
          if (continueStr === (str[i] + str[i + 1] + str[i + 2] + str[i + 3])) return continueStr
        }
        return ''
      }

      if (/(.)\1\1\1/.test(value)) {
        callback(new Error('请勿连续出现4个及以上重复字符'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确格式的密码'))
      } else {
        if ((/[a-z]/.test(value) + /[A-Z]/.test(value) + /[0-9]/.test(value) + /[_！@#-]/.test(value)) < 2) {
          callback(new Error('密码必须同时含有大小写字母、数字、特殊字符中的两种'))
        } else {
          let str = validateContinue(value)
          if (str) {
            callback(new Error(`存在连续字符${str}`))
          } else {
            callback()
          }
        }
      }  
    },
    // 生成二维码
    initQRCode (userId) {
      this.userId = userId
      this.bindWxVisible = true
      const appId = process.env.VUE_APP_WX_APPID
      this.$nextTick(() => {
        let call_back_domain_name = `${window.location.origin}/bindWxLoading?userId=${userId}`
        let obj = new WxLogin({
          self_redirect: true,
          id:"login_container",
          appid: appId,
          scope: "snsapi_login",
          redirect_uri: encodeURIComponent(call_back_domain_name),
          state: Math.random(),
          style: "white",
          href: ""
        })
        console.log(obj)
      })
    },
    unBindWx (userId) {
      this.$confirm('确定要解绑该账号的微信吗？')
        .then(async () => {
          try {
            const { code } = await unbindWxApi({ userId: userId })
            if (code === 200) {
              this.$message.success('解绑成功')
              this.initTable()
            }
          } catch (error) {
            console.log(error)
          }
        })
        .catch(() => {})
    }
  },
  created () {
    this.initTable()
    this.getRoleList()
    this.getAllDataPermissionGroup()
  },
  mounted () {
    window.addEventListener('message', ({data}) => {
      if (data.source === 'bindWxPage') {
        const { code, message } = data
        this.bindWxVisible = false
        if (code === 200) {
          this.$message.success('绑定成功')
          this.initTable()
        } else {
          this.$message.error(message)
        }
      }
    }, false)
  },
  destroyed () {
    try {
      window.removeEventListener('message', ()=>{}, false)
    } catch (error) {
      console.log(error)
    }
  }
}
</script>
<style lang="less" scoped>
  @import url('../mixin.less');

  .account-wrap {
    padding-top: 30px;
    .el-form-item .el-input {
      margin-bottom: 0;
    }
    .flex-row {
      display: flex;
    }
    .el-select {
      width: 100%;
    }
    .modify-form {
      display: flex;
      &>div {
        width: 50%;
      }
      .el-input, .el-select {
        width: 300px;
      }
    }
  }
  .tips{
    // width: 100%;
    margin: 12px 0 10px 23px;
    background: #F2F4F8;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    padding: 10px 20px 10px 20px;
    box-sizing: border-box;
    .title{
      color: #4B7EFE;
      line-height: 24px;
    }
    .des{
      color: #666666;
      line-height: 24px;
    }
  }
  .btn-style{
    width: 100px;
    height: 40px;
    background: #EEEEEE;
    border-radius: 2px;
    border: none;
    &.primary{
      background: #3669EB;
      box-shadow: 0px 2px 6px 0px rgba(16, 67, 193, 0.2);
    }
  }
  // /deep/.el-dialog .el-dialog__body{
  //   padding-right: 60px;
  // }
</style>